<template>
  <div>
    <el-row :gutter="20">
      <!--      图书矩阵-->
      <el-col :span="12">
        <!--        搜索-->
        <el-row>
          <el-input prefix-icon="el-icon-search" placeholder="搜索..." v-model="search"/>
        </el-row>
        <!--        项目-->
        <el-row>
          <el-col :span="6" v-for="i in pagedData" :key="i.id">
            <book-item
                :id="i.id"
                :title="i.title"
                :price="i.price"
                :url="i.imgUrl"
                custom
                @click="edit(i)"
            />
          </el-col>
        </el-row>
        <!--        分页-->
        <el-row>
          <el-pagination
              :total="this.filteredData.length"
              :page-size="itemsPerPage"
              hide-on-single-page
              :current-page.sync="page"
          />
        </el-row>
      </el-col>
      <!--      表单-->
      <el-col :span="12">
        <el-card>
          <template v-slot:header>
            <h3>{{ newItem ? '新建' : '修改' }}</h3>
          </template>
          <el-form :model="form" ref="form" :rules="rules">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title"/>
            </el-form-item>
            <el-form-item label="类目" prop="category">
              <el-select v-model="form.category" placeholder="-- 请选择 --">
                <el-option v-for="i in categories" :value="i.id" :label="i.name" :key="i.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author"/>
            </el-form-item>
            <el-form-item label="出版社" prop="publisher">
              <el-input v-model="form.publisher"/>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :precision="2" :step="0.01" :min="0"/>
            </el-form-item>
            <el-form-item label="封面">
              <el-upload action="#"
                         ref="img"
                         :auto-upload="false"
                         :limit="1"
                         accept=".jpg,.png"
                         list-type="picture-card"
              >
                <template>
                  <i class="el-icon-plus"></i>
                </template>
                <template v-slot:file="{file}">
                  <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                  >
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button @click="reset">重置</el-button>
              <el-button type="danger" @click="del" :disabled="newItem">下架</el-button>
              <el-button type="primary" @click="submit">提交</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import BookItem from "@/components/books/BookItem";

export default {
  name: "ManageBookView",
  components: {BookItem},
  data() {
    return {
      books: [],
      page: 1,
      search: "",
      itemsPerPage: 16,
      form: {
        id: undefined,
        title: "",
        price: 0.0,
        author: "",
        category: null,
        publisher: "",
      },
      categories: [],
      rules: {
        title: [
          {required: true, message: '请填写标题！'}
        ],
        price: [
          {type: 'number', message: '价格必须是数字！'}
        ],
        author: [
          {required: true, message: '请填写作者！'}
        ],
        category: [
          {required: true, message: '请填写类别！'}
        ],
        publisher: [
          {required: true, message: '请填写出版社！'}
        ],
      }
    }
  },
  methods: {
    fetchBooks() {
      let loading = this.$loading({
        fullscreen: true,
        lock: true
      });
      axios.get('/api/book/list')
          .then(res => {
            this.books = res.data;
            loading.close();
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
            loading.close();
          })
    },
    fetchCategories() {
      axios.get("/api/book/fetchCategories")
          .then(res => {
            this.categories = res.data
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    edit(item) {
      this.form.id = item.id
      this.form.title = item.title
      this.form.price = item.price
      this.form.author = item.author
      this.form.category = item.categoryId
      this.form.publisher = item.publisher
    },
    submit() {
      const file = this.$refs.img.uploadFiles[0]
      const config = {
        headers: {'Content-Type': 'multipart/form-data'}
      };
      const {
        id, title, price, author, category, publisher
      } = this.form;
      if (this.newItem) {  // 新项目
        if (!file) {
          return;
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            const rawFile = file.raw;
            let formData = new FormData();
            formData.append("title", title);
            formData.append("author", author);
            formData.append("publisher", publisher);
            formData.append("categoryId", category);
            formData.append("price", price);
            formData.append("img", rawFile);

            axios.post("/api/manage/book/add", formData, config)
                .then(() => {
                  this.$message({
                    message: '添加成功！',
                    type: 'success'
                  });
                  this.fetchBooks()
                })
                .catch(e => {
                  if (e.response) {
                    this.$message({
                      message: `未知的服务器错误 代码${e.response.status}`,
                      type: "error"
                    });
                  } else {
                    this.$message({
                      message: `未知的错误`,
                      type: "error"
                    });
                  }
                })
          }
        });
      } else {
        let formData = new FormData();
        let addParam = (key, value) => {
          if (value !== null && value !== undefined && value !== "") {
            formData.append(key, value);
          }
        };
        if (file) {
          formData.append("img", file.raw);
        }
        addParam("id", id);
        addParam("author", author);
        addParam("title", title);
        addParam("publisher", publisher);
        addParam("categoryId", category);
        addParam("price", price);

        axios.post("/api/manage/book/edit", formData, config)
            .then(() => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.fetchBooks()
            })
            .catch(e => {
              if (e.response) {
                this.$message({
                  message: `未知的服务器错误 代码${e.response.status}`,
                  type: "error"
                });
              } else {
                this.$message({
                  message: `未知的错误`,
                  type: "error"
                });
              }
            })
      }
    },
    del() {
      axios.post(`/api/manage/book/del`, {id: this.form.id})
          .then(() => {
            this.$message({
              message: "下架成功！",
              type: "success"
            })
            this.reset()
            this.fetchBooks()
          })
          .catch(e => {
            if (e.response) {
              this.$message({
                message: `未知的服务器错误 代码${e.response.status}`,
                type: "error"
              });
            } else {
              this.$message({
                message: `未知的错误`,
                type: "error"
              });
            }
          })
    },
    reset() {
      this.$refs.form.resetFields()
      this.form.id = undefined
      this.$refs.img.clearFiles()
    }
  },
  computed: {
    filteredData() {
      if (!this.search) {
        return this.books
      } else {
        return this.books.filter(val => val.title.includes(this.search))
      }
    },
    pagedData() {
      return this.filteredData.slice((this.page - 1) * this.itemsPerPage, this.page * this.itemsPerPage)
    },
    lessItems() {  // 对当前页面而言, 还有多少条目可以填满页面
      return this.itemsPerPage - this.pagedData.length
    },
    newItem() {
      return !this.form.id
    }
  },
  beforeMount() {
    this.fetchBooks();
    this.fetchCategories();
  }
}
</script>

<style scoped>

</style>